package com.cxd.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cxd.springcloud.entities.Payment;
import com.cxd.springcloud.feign.PaymentFeign;
import com.cxd.springcloud.vo.CommonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class CircleBreakeController {

    public static final String SERVICED_URL = "http://alibabacloud-nacos-provider";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    // @SentinelResource(value = "fallback")
    // @SentinelResource(value = "fallback",fallback = "fallbackHandle")//只负责业务异常
    // @SentinelResource(value = "fallback",blockHandler = "blockHandlerException")//只负sentinel的配置违规
    @SentinelResource(value = "fallback",fallback = "fallbackHandle",blockHandler = "blockHandlerException",exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable("id")Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICED_URL + "/paymentSql/" + id, CommonResult.class, id);
        if(id == 4){
            throw new IllegalArgumentException("IllegalAccessException,非法参数异常.....");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该id没有对应记录,空指针异常");
        }
        return result;
    }

    public CommonResult fallbackHandle(Long id,Throwable e) {
        return new CommonResult("444", "兜底异常,runtimeException---->" + e.getMessage(), new Payment(id, null));
    }

    public CommonResult blockHandlerException(Long id, BlockException e) {
        return new CommonResult("445", "兜底异常,BlockException---->" + e.getMessage(), new Payment(id, null));
    }

    //===================================openfeign
    @Resource
    private PaymentFeign paymentFeign;

    @GetMapping("/consumer/openfeign/fallback/{id}")
    public CommonResult<Payment> openfeignFallback(@PathVariable("id")Long id) {
        return paymentFeign.fallback(id);
    }

}
